package com.yjzx.util.redisson.service.impl;

import com.yjzx.util.RedisConst;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yjzx.util.common.execption.UtilException;
import com.yjzx.util.common.util.json.JacksonUtil;
import com.yjzx.util.redisson.service.CacheOpsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
public class CacheOpsServiceImpl implements CacheOpsService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public <T> T getCacheData(String key, Class<T> clazz) {
        String str = this.redisTemplate.opsForValue().get(key);
        if (RedisConst.TEMP_DATA.equals(str)) {
            throw new UtilException("数据不存在",3001);
        }
        return StringUtils.isEmpty(str) ? null : JacksonUtil.toObj(str, clazz);

    }

    @Override
    public <T> T getCacheData(String key, TypeReference<T> tf) {
        String str = this.redisTemplate.opsForValue().get(key);

        if (RedisConst.TEMP_DATA.equals(str)){
            redisTemplate.opsForValue().set(key, str, RedisConst.TEMP_DATA_TTL, RedisConst.TEMP_DATA_TTL_UNIT);
            throw new UtilException("数据不存在",3001);
        }

        return StringUtils.isEmpty(str) ? null : JacksonUtil.toObj(str, tf);
    }

    @Override
    public void saveData(String key, Object data, Long ttl, TimeUnit timeUnit) {
        String str = data == null ? RedisConst.TEMP_DATA : JacksonUtil.toStr(data);
        if (RedisConst.TEMP_DATA.equals(str)) {
            redisTemplate.opsForValue().set(key, str, RedisConst.TEMP_DATA_TTL, RedisConst.TEMP_DATA_TTL_UNIT);
            throw new UtilException("数据不存在",3001);
        } else {
            redisTemplate.opsForValue().set(key, str, ttl, timeUnit);
        }
    }

}